define(['jquery', 'datatables', 'module/util'], function($, datatables, util){
	var DataTable = function(){
	};
	
	DataTable.prototype = {
		init: function(options){
			var inner_table = new TableInner();
			inner_table.init(options);
			return inner_table;
		}
	};
	var TableInner = function(){
		this.tableId  = "";
		this.sAjaxSource = "";
		this.params = [];
		this.aaSorting=[];
		this.functionList = {};
		this.rawOptions = {};
		this.rawTable = {};
		this.iDisplayStart = [];
		this.bScrollCollapse = false;
		this.sScrollY = {};
	};
	
	
	$.fn.dataTableExt.oApi.fnStandingRedraw = function(oSettings) {
	    oSettings.oApi._fnDraw(oSettings);
	};
	
	TableInner.prototype = {
		init : function(options){
			var $this = this;
			options = $.extend({}, TableInner.prototype.defaults, typeof options == 'object'?  options : {});
			if(!options.tableId || options.tableId .length == 0 ||  !options.sAjaxSource || options.sAjaxSource.length == 0) {
				alert("tableId,sAjaxSource必须提供");
				return;
			}
			if(options.params && typeof options.params == "object") {
				this.params = options.params;
			}
			this.iDisplayStart = options.iDisplayStart;
			this.first =options.first;
			this.tableId = options.tableId;
			this.sAjaxSource = options.sAjaxSource;
			this.aaSorting = options.aaSorting;
			this.functionList = options.functionList;
			this.rawOptions = options.rawOptions;
			this.iDisplayLength = options.iDisplayLength;
			this.autoSearch = options.autoSearch===undefined?true:options.autoSearch;
			this.jumpFlag = options.jumpFlag;
			this.callBack = options.callBack;
			// 固定表头
			this.bScrollCollapse = options.bScrollCollapse;
			this.sScrollY = options.sScrollY;
			
			if(this.iDisplayLength == undefined || this.iDisplayLength == ""){
				this.iDisplayLength = 30;
			}
			if(this.first == undefined){
				this.first =true;
			}
			var cols = [{aTargets : [ '_all' ], "sDefaultContent" : "&nbsp;"}];
			var mData,bSortable,mRender,col;
			 
			$(this.tableId).find("th").each(function(index) {
				if($(this).attr("data-ignore") == "true") {
					return;
				}
				col = {};
		        mData = $(this).attr("data-mData");
		        bSortable = $(this).attr("data-bSortable");
		        mRender = $(this).attr("data-mRender");
                sFormatType = $(this).attr("data-sFormatType");
		        fnCreatedCell = $(this).attr("data-fnCreatedCell");
		        data_index = $(this).attr("data-index");
				var	dataKkey = $(this).attr("data-key");
				if(mData) {
					if(mData.match(/^_fn/i)) {
						col.mData = $this.functionList[mData];
					}else{
						col.mData = mData;
					}
				}
				
				if(bSortable){
					if(bSortable == "false") {
						bSortable = false;
					}	
					col.bSortable = bSortable;
				}
				
				if(mRender){
					col.mRender = $this.functionList[mRender];
				}

                if(sFormatType=="thousand"){
                    col.mRender = function(data){
                        return '<span class="table-align-right">'+numeral(data).format('0,0.00')+'</span>';
                    };
                } else if(sFormatType=="aprate"){
                    col.mRender = function(data){
                    	var num = parseFloat(data);
                        return !/\./.test(num) == true? num += ".0%":num +"%" ;
                    };
                } else if(sFormatType=="percent"){
                    col.mRender = function(data){
                        return numeral(data).format('0.0')+"%";
                    };
                } else if(sFormatType=="dict"){
                	col.mRender = function(data){
                		var __html = "", __dict = (dict[dataKkey] || dict[dataKkey + "_DICT"]);
                		if(__dict == null || __dict == undefined || data == null || data == undefined) {
	                		return __html;
	            		} else {
	            			data = data + "";// 兼容数字
	            		}
            			if(data.indexOf(",") != -1) {
                    		var values = data.split(",");// 翻译多个数据用逗号隔开显示
                    		for(var i in values) {
                    			if(!values[i]) {
                    				continue;
                    			}
        	            		__html += (i == 0 ? "" : ",") + (__dict[values[i]] || "-");
                    		}
                		} else {
    	            		__html += (__dict[data] || "-");
                		}
                		return __html;
					}
                }
				if(fnCreatedCell){
					col.fnCreatedCell = $this.functionList[fnCreatedCell];
				}
				if(data_index){
					index = data_index;
				}
				
				col.aTargets = [index];
				cols.push(col);
				
			});
		    this.aoColumns = cols;
			return this;
		},
		setParams: function(params){
			this.params=params;
		},
		getParams:function(){
			return this.params;
		},
		create: function(){
			var $this = this;
			this.rawTable = $($this.tableId).dataTable($.extend({},{
				bJQueryUI : true,//设置bJQueryUI和sDom，去掉table-header
		        sDom : 'lfrtip',
				bPaginate :true,
				bFilter :false,
				bSort : true,
				bInfo : true,
				bProcessing : true,
				bLengthChange : false,
				iDisplayLength :$this.iDisplayLength,
				sPaginationType : "full_numbers",
		        bServerSide : true,
		        aaSorting :$this.aaSorting,
		        aoColumnDefs : $this.aoColumns,
		        sAjaxSource : $this.sAjaxSource,
		        bScrollCollapse : $this.bScrollCollapse,// 固定表头
		        sScrollY : $this.sScrollY,
		        fnServerData : function( sSource, aoData, fnCallback){
		        	if($this.autoSearch && $this.first){
		        		fnCallback({
		        			iTotalDisplayRecords: 0,
		        			iTotalRecords: 0,
		        			sColumns: null,
		        			aaData:[],
		        			sEcho: "1"
		        		});
		        		$this.first = false;
		        		return;
		        	}else{
			        	$this.first = false;
			        	$this.doQuery({
			        		sSource : sSource,
			        		new_aoData : aoData.concat($this.params).concat($this.iDisplayStart),
			        		success : function(resp) {
			     				fnCallback(resp); //服务器端返回的对象的returnObject部分是要求的格式
			        		},
			        		callBack : function(resp) {
			        			if($this.callBack) {
			        				$this.callBack(resp);
			        			}
			        		}
				        });
		        	}
		        },    
		        oLanguage : {
					sLengthMenu : "每页显示 _MENU_ 条记录",
					sInfo : "共 _TOTAL_ 条记录 / 当前第 _START_ 到 _END_ 行",
					sInfoEmpty : "共 _TOTAL_ 条记录",
					oPaginate : {
						sFirst : "首页",
						sPrevious : "前一页",
						sNext : "后一页",
						sLast : "尾页",
					},
					sZeroRecords : "请选择条件查询",
					sProcessing: "正在查询..."
				},
			},$this.rawOptions));
			if($this.jumpFlag){
				$this.pageJump();
			}
			return this;
		},
		pageJump : function(){
			var $this = this;
			var _html = '<div style="float: right;"><input type="text" class="page-jump" style="width: 37px;"><span>页</span><button class="jump-button btn btn-primary" style="padding: 7px;">跳转</button></div>';
			var paginate = $($this.tableId).parent();
			paginate.append(_html);
			$(".jump-button").on('click',function(){
				var reg = new RegExp("^[0-9]*[1-9][0-9]*$");
				var jumpNumber = $.trim($(".page-jump").val());
				if(!reg.test(jumpNumber)){  
					$.pnotify({
					    text: "请输入正确的页码数",
					    type: 'error',
					    delay : '3000'
					});
					return false;
			    } 
				var trLength = $this.rawTable['fnGetNodes'].apply($this.rawTable);
				if(trLength.length==0){
					$(".page-jump").val('1');
				}
				$this.invoke('fnPageChange',[parseInt(jumpNumber)-1]);
			});
		},
		invoke : function(method_name, arguments){
			/*var args =[];
			if(arguments.length > 1) {
				for(var i=1;i<arguments.length;i++) {
					args.push(arguments[i]);
				}
			}else{
				args = null;
			}*/ 
			this.rawTable[method_name].apply(this.rawTable,arguments);
			if(method_name == 'fnDraw' && this.jumpFlag){
				$(".page-jump").val('');
			}
		},
		doQuery : function(obj) {
			$.ajax( {
     			type : "POST", 
     			url : obj.sSource, 
     			contentType : 'application/json; charset=UTF-8',
     			dataType : "json",
     			data : util.stringify_aoData(obj.new_aoData), 
     			success : function(resp) {
     				try {
     					if(obj && obj.success) {
     						obj.success(resp); //服务器端返回的对象的returnObject部分是要求的格式
     					}     					
	     				if(obj && obj.callBack){
	     					obj.callBack(resp);
	     				}
     					$('.dataTables_empty').text('暂无您要查询的数据！');
     				} catch(e) {
	     				$(".dataTables_processing").hide();
	     				alert("数据已经查询成功，部分数据缺失或配置错误导致JS异常，可能引起数据显示不完全，请联系开发！");
     				}
     			},
     			error : function(resp) {
     				$(".dataTables_processing").hide();
     				if(obj && obj.error) {
 						obj.error(resp); //服务器端返回的对象的returnObject部分是要求的格式
 					}
     			}
     		});
		}
	};
	
	TableInner.prototype.defaults = {
		sAjaxSource : "",
		tableId : "",
		params :[],
		iDisplayStart :[],
		jumpFlag : true,//设置跳转到第几页的按钮，默认为true,如不需要，设为false
		aaSorting :[[0,"asc"]],
		functionList :{},
		rawTable :{},
		bScrollCollapse : false
	};
	return new DataTable();
});